package com.bj58.mis.apm.server.kylin;

import com.bj58.mis.apm.server.kylin.model.Project;
import com.bj58.mis.apm.server.kylin.util.FileUtil;
import com.bj58.mis.apm.server.kylin.util.JsonUtil;
import com.bj58.mis.apm.server.kylin.util.TimeUtil;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ReadZipMain {

    public static void main(String[] args) throws Exception {

        String basepath = "D:\\temp\\kybot_2018_06_01_11_18_58_B46850\\kybot_2018_06_01_11_18_58\\";
        String filepath = "metadata\\project\\student.json";
        //readProjectAllInfo(basepath+filepath);

        System.out.println(Long.bitCount(127L));
        System.out.println(127 | 1);
        System.out.println(1L << 6);
        Long l = 1L << 6;
        System.out.println(Long.toBinaryString(l));

        String groupsD = "groupsD=[";
        String filterD = "filterD=[";
        String end = "]";
        String str = "2018-06-11 20:10:36,928 INFO  [Query 7b3c7c9c-5131-4d4f-8fa6-970d695e62e6-47712] gtrecord.GTCubeStorageQueryBase:170 : Cuboid identified: cube=student, cuboidId=47, groupsD=[ODS.O_M_T_STUDENT.CITY, ODS.O_M_T_SUBJECT.SUBJECT_NAME, ODS.O_M_T_STUDENT.SEX], filterD=[], limitPushdown=50000, limitLevel=LIMIT_ON_RETURN_SIZE, storageAggr=true";
        String s = str.substring(str.indexOf(groupsD) + groupsD.length(),str.indexOf(end,str.indexOf(groupsD)));
        s =  s.replaceAll("ODS.","").replaceAll(" ","");
        System.out.println(s);
        s = str.substring(str.indexOf(filterD) + filterD.length(),str.indexOf(end,str.indexOf(filterD)));
        s =  s.replaceAll("ODS.","").replaceAll(" ","");
        System.out.println(s);

        List<Project> list = new ArrayList<>();
        Project p1 = new Project();
        p1.setUuid("123");
        p1.setName("123");
        list.add(p1);
        Project p2 = new Project();
        p2.setUuid("1234");
        p2.setName("1234");
        list.add(p2);
        String json = JsonUtil.toString(list);
        System.out.println(json);
        list = JsonUtil.fromJson(json, new TypeToken<List<Project>>(){}.getType());
        System.out.println(list.toString());
        System.out.println(JsonUtil.toString(list));
        System.out.println(list.get(0).getUuid());
        /*
        File file = new File(basepath+"logs\\kylin.log");
        List list = KylinLogUtil.readQueryInfo(file);
        list.forEach(m->{
            System.out.println(m);
        });
        */
    }

    /**
     * 按项目加载所有信息
     * @param filepath 文件路径
     */
    public static void readProjectAllInfo(String filepath){
        File projectfile = new File(filepath);
        String str = FileUtil.readFile(projectfile);
        if(FileUtil.isSuccess(str)){
            Map map = JsonUtil.fromJson(str);
            printProject(map);

            List<Map<String, String>> cubes = (List)map.get("realizations");

            cubes.forEach(cube ->{
                if("CUBE".equals(cube.get("type"))){
                    String cubefile = projectfile.getParentFile().getParent() + "\\cube\\" + cube.get("realization") + ".json";
                    String cubedescfile = projectfile.getParentFile().getParent() + "\\cube_desc\\" + cube.get("realization") + ".json";
                    Map cubemap = JsonUtil.fromJson(FileUtil.readFile(cubefile));
                    Map cubedescmap = JsonUtil.fromJson(FileUtil.readFile(cubedescfile));
                    printCube(cubemap, cubedescmap);

                    List<Map<String, Object>> segments = (List)cubemap.get("segments");
                    segments.forEach(seg->{
                        readPrintJob(seg, projectfile.getParentFile().getParentFile().getParent());
                    });
                }
            });


        }else{
            System.err.println("err:"+str);
        }
    }

    /**
     * 在project中取值
     * @param p
     */
    public static void printProject(Map p){
        System.out.println("=======Project=======");
        System.out.println("名称："+p.get("name"));
        System.out.println("创建时间："+TimeUtil.format(new Date(((Double)p.get("create_time_utc")).longValue())));
        System.out.println("最后修改时间："+TimeUtil.format(new Date(((Double)p.get("last_modified")).longValue())));
    }

    public static void printCube(Map cube, Map cubedesc){
        System.out.println("=======Cube=======");
        System.out.println("名称："+cube.get("name"));
        System.out.println("创建时间："+TimeUtil.format(new Date(((Double)cube.get("create_time_utc")).longValue())));
        System.out.println("最后修改时间："+TimeUtil.format(new Date(((Double)cubedesc.get("last_modified")).longValue())));
        System.out.println("状态："+cube.get("status"));

        System.out.println("dimensions：" + cubedesc.get("dimensions"));
        System.out.println("measures：" + cubedesc.get("measures"));
        System.out.println("rowkey：" + cubedesc.get("rowkey"));
    }

    public static void readPrintJob(Map seg, String basepath){

        System.out.println("======Job======");
        System.out.println("last_build_job_id："+seg.get("last_build_job_id"));
        System.out.println("构建类型："+seg.get("name"));
        System.out.println("最后构建时间："+TimeUtil.format(new Date(((Double)seg.get("last_build_time")).longValue())));
        System.out.println("读取记录："+seg.get("input_records"));
        System.out.println("构建后文件大小："+seg.get("size_kb")+"kb");
        System.out.println("膨胀倍数：" + (Double)seg.get("size_kb")*1024/(Double)seg.get("input_records_size"));
        System.out.println("dictionaries："+seg.get("dictionaries"));
        System.out.println("rowkey_stats："+seg.get("rowkey_stats"));

        String jobfilepath = basepath + "\\jobs\\" + seg.get("last_build_job_id")+".json";
        String jobstr = FileUtil.readFile(jobfilepath);
        if(FileUtil.isSuccess(jobstr)){
            Map job = JsonUtil.fromJson(jobstr);
            System.out.println("名称：" + job.get("name"));
            System.out.println("类型："+job.get("type"));
            System.out.println("构建开始时间："+ TimeUtil.format(new Date(((Double)job.get("exec_start_time")).longValue())));
            System.out.println("构建结束时间："+ TimeUtil.format(new Date(((Double)job.get("exec_end_time")).longValue())));
            System.out.println("持续时间："+ TimeUtil.duration(((Double)job.get("exec_start_time")).longValue(),((Double)job.get("exec_end_time")).longValue()));
            System.out.println("MR等待时间："+ TimeUtil.duration(((Double)job.get("mr_waiting")).longValue() * 1000));
            System.out.println("执行中断时间："+ TimeUtil.duration(((Double)job.get("exec_interrupt_time")).longValue() * 1000));

            List<Map<String, Object>> steps = (List)job.get("steps");
            steps.forEach( step -> {
                printSteps(step);
            });
        }
    }

    public static void printSteps(Map step){
        System.out.println("====Step-" + step.get("sequence_id") + "====");
        System.out.println("名称："+step.get("name"));
        System.out.println("状态："+step.get("step_status"));
        System.out.println("命令："+step.get("exec_cmd"));
        System.out.println("命令类型："+step.get("cmd_type"));
        System.out.println("开始时间："+ TimeUtil.format(new Date(((Double)step.get("exec_start_time")).longValue())));
        System.out.println("结束时间："+ TimeUtil.format(new Date(((Double)step.get("exec_end_time")).longValue())));
        System.out.println("等待时间："+ TimeUtil.duration(((Double)step.get("exec_wait_time")).longValue() * 1000));
        System.out.println("info："+step.get("info"));
    }
}
